package stdio.costa.imoca.card;

import stdio.costa.imoca.utils.AsposeUtils;

import com.aspose.words.Cell;
import com.aspose.words.CompositeNode;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.IReplacingCallback;
import com.aspose.words.Node;
import com.aspose.words.ReplaceAction;
import com.aspose.words.ReplacingArgs;
import com.aspose.words.Shape;

public class MarkableImageReplacingCallback implements IReplacingCallback {

	private final String text;
	
	private final byte[] image;
	
	private final DocumentBuilder builder;
	
	public MarkableImageReplacingCallback(String text, byte[] image, DocumentBuilder builder) {
		this.text = text;
		this.image = image;
		this.builder = builder;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public int replacing(ReplacingArgs arg) throws Exception {
		Node matchedNode = arg.getMatchNode();
		if(matchedNode != null) {
			CompositeNode paragraph = matchedNode.getParentNode();
			AsposeUtils.replace(paragraph, text, "");
			Cell parent = (Cell) paragraph.getParentNode();			
			builder.moveTo(paragraph);
			Shape shape = builder.insertImage(image);
			shape.setWidth(parent.getCellFormat().getWidth());
			shape.setHeight(parent.getParentRow().getRowFormat().getHeight());
		}
		return ReplaceAction.SKIP;
	}

}
